package com.jimmyhsu.ecnudaowei.coursetable.bulletin;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jimmyhsu.ecnudaowei.Db.UserDbHelper;
import com.jimmyhsu.ecnudaowei.MyApplication;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.Utils.TextViewUtils;
import com.jimmyhsu.ecnudaowei.common.Config;
import com.jimmyhsu.ecnudaowei.common.views.BulletinItemDecoration;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * Created by jimmyhsu on 2017/4/18.
 */

public class BulletinActivity extends AppCompatActivity implements XRecyclerView.LoadingListener {

    private static final String EXTRA_COURSE_ID = "extra_course_id";

    @BindView(R.id.bulletin_rv)
    XRecyclerView mBulletinRv;

    private List<Bulletin> mBulletins = new ArrayList<>();
    private String mCourseId;
    private MyApplication mApp;

    private UserDbHelper mDbHelper;
    private BulletinAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bulletin);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("公告");
        ButterKnife.bind(this);
        mDbHelper = UserDbHelper.getInstance(this);
        mApp = MyApplication.getInstance(this);
        initCourseId();
        getDataFromDatabase();
        initBulletinList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        downloadBulletin();
    }

    private void downloadBulletin() {
        DownloadBulletinService service = new Retrofit.Builder()
                .baseUrl(Config.SERVER_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build()
                .create(DownloadBulletinService.class);
        Call<String> call = service.getBulletin(mApp.getName(),
                mApp.getPassword(),
                mCourseId);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.code() == 200) {
                    try {
                        JSONObject responseObj = new JSONObject(response.body());
                        int code = responseObj.getInt("code");
                        if (code == 200) {
                            mBulletins.clear();
                            JSONArray bulletinArray = responseObj.getJSONArray("data");
                            int length = bulletinArray.length();
                            for (int i = 0; i < length; i++) {
                                JSONObject bulletinJson = bulletinArray.getJSONObject(i);
                                mBulletins.add(new Bulletin(bulletinJson.getString("course_id"),
                                        Integer.parseInt(bulletinJson.getString("b_id")),
                                        bulletinJson.getString("title"),
                                        bulletinJson.getString("content"),
                                        bulletinJson.getString("release_time"),
                                        bulletinJson.getString("author"),
                                        bulletinJson.getString("image_url")));
                            }
                            mAdapter.notifyDataSetChanged();
                            saveToDb();
                        } else if (code == 500) {
                            Toast.makeText(BulletinActivity.this, "数据库异常", Toast.LENGTH_SHORT).show();
                        } else if (code == 501) {
                            Toast.makeText(BulletinActivity.this, "您没有权限查看此课程的公告", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(BulletinActivity.this, "未知异常", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(BulletinActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                }
                mBulletinRv.refreshComplete();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                mBulletinRv.refreshComplete();
                Toast.makeText(BulletinActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveToDb() {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        db.execSQL("delete from " + Bulletin.TABLE_NAME + " where course_id='" + mCourseId + "'");
        for (Bulletin b : mBulletins) {
            ContentValues values = new ContentValues();
            values.put(Bulletin.COL_TITLE, b.getTitle());
            values.put(Bulletin.COL_CONTENT, b.getContent());
            values.put(Bulletin.COL_B_ID, b.getbId());
            values.put(Bulletin.COL_AUTHOR, b.getAuthor());
            values.put(Bulletin.COL_COURSE_ID, b.getCourseId());
            values.put(Bulletin.COL_RELEASE_DATE, b.getCourseId());
            values.put(Bulletin.COL_IMAGEURL, b.getImageUrl());
            db.insert(Bulletin.TABLE_NAME, null, values);
        }
        db.close();
    }

    private void initCourseId() {
        mCourseId = getIntent().getStringExtra(EXTRA_COURSE_ID);
    }

    private void getDataFromDatabase() {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + Bulletin.TABLE_NAME +
                " where course_id=? order by " + Bulletin.COL_B_ID + " desc",
                new String[]{mCourseId});
        while (cursor.moveToNext()) {
            mBulletins.add(new Bulletin(mCourseId,
                    cursor.getInt(cursor.getColumnIndex(Bulletin.COL_B_ID)),
                    cursor.getString(cursor.getColumnIndex(Bulletin.COL_TITLE)),
                    cursor.getString(cursor.getColumnIndex(Bulletin.COL_CONTENT)),
                    cursor.getString(cursor.getColumnIndex(Bulletin.COL_RELEASE_DATE)),
                    cursor.getString(cursor.getColumnIndex(Bulletin.COL_AUTHOR)),
                    cursor.getString(cursor.getColumnIndex(Bulletin.COL_IMAGEURL))));
        }
        cursor.close();
    }

    private void initBulletinList() {
        mBulletinRv.setAdapter(mAdapter = new BulletinAdapter(this, mBulletins));
        mBulletinRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mBulletinRv.setLoadingMoreProgressStyle(ProgressStyle.Pacman);
        mBulletinRv.setPullRefreshEnabled(true);
        mBulletinRv.setLoadingMoreEnabled(true);
        mBulletinRv.setLoadingListener(this);
        mBulletinRv.addItemDecoration(new BulletinItemDecoration(this, 6));
    }


    public static void startActivity(Context context, String courseId) {
        Intent intent = new Intent(context, BulletinActivity.class);
        intent.putExtra(EXTRA_COURSE_ID, courseId);
        context.startActivity(intent);
    }

    @Override
    public void onRefresh() {
        downloadBulletin();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.id_bulletin_add)
    void addBulletin() {
        AddBulletinActivity.startActivity(this, mCourseId);
    }

    static class BulletinAdapter extends RecyclerView.Adapter<BulletinViewHolder> {

        private LayoutInflater mInflater;
        private List<Bulletin> mDatas;
        private Context mContext;

        BulletinAdapter(Context context, List<Bulletin> datas) {
            mDatas = datas;
            mInflater = LayoutInflater.from(context);
            mContext = context;
        }

        void setDatas(List<Bulletin> datas) {
            mDatas = datas;
            notifyDataSetChanged();
        }

        @Override
        public BulletinViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View convertView = mInflater.inflate(R.layout.bulletin_item, parent, false);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = (int) v.getTag();
                    Bulletin b = mDatas.get(pos);
                    BulletinDetailActivity.startActivity(mContext,
                            b.getCourseId(), b.getbId(),
                            b.getTitle(), b.getContent(),
                            b.getAuthor(), b.getReleaseDate(),
                            b.getImageUrl());
                }
            });
            return new BulletinViewHolder(convertView);
        }

        @Override
        public void onBindViewHolder(BulletinViewHolder holder, int position) {
            holder.convertView.setTag(position);
            Bulletin bulletin = mDatas.get(position);
            String dateStr = bulletin.getReleaseDate();
            dateStr = dateStr.replaceFirst("-", "年");
            dateStr = dateStr.replaceFirst("-", "月");
            dateStr = dateStr.replaceFirst(" ", "日 ");
            dateStr = dateStr.substring(0, dateStr.length() - 3);
            holder.title.setText(bulletin.getTitle());
            holder.author.setText(bulletin.getAuthor());
            holder.releaseTime.setText(dateStr);
            holder.content.setText(bulletin.getContent());
            if (!bulletin.getImageUrl().equals("")) {
                holder.image.setVisibility(View.VISIBLE);
                Glide.with(mContext).load(Config.SERVER_URL + bulletin.getImageUrl())
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .centerCrop()
                        .into(holder.image);
            } else {
                holder.image.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }
    }

    static class BulletinViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.id_bulletin_title)
        TextView title;
        @BindView(R.id.id_bulletin_author)
        TextView author;
        @BindView(R.id.id_bulletin_release_time)
        TextView releaseTime;
        @BindView(R.id.id_bulletin_content)
        TextView content;
        @BindView(R.id.id_bulletin_img)
        ImageView image;
        View convertView;
        public BulletinViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            convertView = itemView;
        }
    }

    interface DownloadBulletinService {
        @FormUrlEncoded
        @POST("phpprojects/course/downloadBulletin.php")
        Call<String> getBulletin(@Field("username") String username,
                                 @Field("password") String password,
                                 @Field("course_id") String courseId);

    }
}
